﻿using SIE.SCADA.ZemtDemo;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading;
using Models;
using SIE.SCADA.ZemtDemo.Common;
using SIE.SCADA.ZemtDemo.MqClient.Model;
using SIE.SCADA.SqlSugar;
using SIE.SCADA.Common.Log;
using static SCADA_DAQ.ZEMT.Server.MatcfgManager;
using Model.Core;

namespace SCADA_DAQ.ZEMT.Server
{
    /// <summary>
    /// 配置上传
    /// </summary>
    public class MatManager : MqMangerBase<MatManager>
    {
        MatcfgManager matcfgManager;
        private smdc_disid_t _Disid_T;
        private bool _refresh;
        QuosExport quosExport = new QuosExport();
        public string linename = Env.LineName.Value;
        CurMatcfg _curMatcfg = new CurMatcfg();


        public MatManager()
        {
            matcfgManager = MatcfgManager.CreateInstance();
            matcfgManager.MatcfgHandler += MatcfgManager_MatcfgHandler;
            matcfgManager.Start();
        }

        private void MatcfgManager_MatcfgHandler(object sender, EventArgs e)
        {
            _curMatcfg =  e as CurMatcfg;
            _refresh = true;
        }

        private void Loop()
        {
            while(!_stop)
            {
                try
                {
                    CheckUpload();
                }
                catch (Exception ex)
                {
                    Logger.Error($"服务器上传数据失败：{ex.Message}！");
                }
                Thread.Sleep(3000);
            }
        }
        //修改状态，请求上传配置信息
        private void CheckUpload()
        {
            using (var ctx = pgsql.GetClient())
            {
                try
                {
                    if (pgsql.DBClient is SmdcOrmClient ormClient)
                    {
                        var upload = ormClient.SqlSugarClient.Queryable<smdc_disid_t>().Where(m => m.state_int == (int)State.UpdLoad).OrderBy(m => m.endtime).First();
                        _Disid_T = upload;
                        if (upload != null)
                        {
                            quosExport.CreateQuos(_Disid_T.disidno, _Disid_T.serial_number);
                            List<TempdatasItem> tempdatasItems = new List<TempdatasItem>();
                            List<MaininfosItem> maininfosItems = new List<MaininfosItem>();
                            TempdatasItem tempdatasItem = new TempdatasItem();
                            tempdatasItem.pono = upload.poid;
                            tempdatasItem.pmid = upload.matid;
                            tempdatasItem.productsn = upload.serial_number;
                            var materials = ormClient.SqlSugarClient.Queryable<scada_material_record>().
                                Where(m => m.serial_number_str == upload.serial_number && m.disidno == upload.disidno).
                                OrderBy(m=>m.jobstep_code_str).ToList();
                            if (!materials.Any())
                            {
                                SubmitDB.Sumbit_SMDC_Disid(upload.serial_number,upload.disidno,State.UploadError);
                                Logger.Info("该SN没有任何上传配置信息！");
#if !DEBUG
                    return;
#endif
                            }
                            //获取最新的配置信息
                            if (!Match(upload.matid))
                            {
                                //SubmitDB.Sumbit_SMDC_Disid(upload.Serial_Number, upload.DisidNo, State.UploadError);
                                Logger.Info("没有获取到最新的配置信息！");
#if !DEBUG
                    return;
#endif
                            }
                            var matCfgs = ormClient.SqlSugarClient.Queryable<scada_matcfg>().
                                Where(it => it.matid == upload.matid).OrderBy(m => m.index).ToList();
                            if (matCfgs.Any())
                            {
                                foreach (var matCfg in matCfgs)
                                {
                                    var material = materials.Where(m => m.matcode == matCfg.childmatid).FirstOrDefault();
                                    if (material != null)
                                    {
                                        MaininfosItem maininfosItem = new MaininfosItem();
                                        maininfosItem.mid = material.matcode;
                                        maininfosItem.mname = matCfg.childname;
                                        maininfosItem.sort = (matCfg.index).ToString();
                                        if (matCfg.batchmatch == "1")
                                        {
                                            maininfosItem.batch = material.sn;
                                        }
                                        else
                                        {
                                            maininfosItem.sn = material.sn;
                                        }
                                        maininfosItems.Add(maininfosItem);
                                    }
                                    else
                                    {
                                        //没有匹配的物料要报错并停止上传配置
                                        SubmitDB.Sumbit_SMDC_Disid(upload.serial_number, upload.disidno, State.UploadError);
                                        Logger.Info($"没找到该物料：{matCfg.childmatid}的过站记录，请检查后重新上传！");
#if !DEBUG
                            return;
#endif
                                    }
                                }
                                tempdatasItem.pmname = matCfgs.FirstOrDefault()?.cname;
                                tempdatasItems.Add(tempdatasItem);
                                tempdatasItem.maininfos = maininfosItems;
                                MatRecord matRecord = new MatRecord() { tempdatas = tempdatasItems };
                                Send(matRecord);
                            }
                            else
                            {
                                SubmitDB.Sumbit_SMDC_Disid(upload.serial_number, upload.disidno, State.UploadError);
                                Logger.Warn("没找到该物料编号匹配的上传配置！");
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger.Error(ex.Message);
                }

            }
        }

        bool Match(string matid)
        {
            bool res = false;
            matcfgManager.RequestMatcfg(matid);
#if DEBUG
            matcfgManager.RevceiveTest();
#endif

            var overtime = Env.MatcfgOvertime.Value.ObjToInt() * 60;
            for (int i = 0; i < overtime; i++)
            {
                if (_refresh && _curMatcfg.Matcfgs.ContainsKey(matid))
                {
                    res = true;
                    break;
                }
                Thread.Sleep(1000);
            }
            return res;
        }

        //配置上传
        void Send(MatRecord matRecord)
        {
            var res = mqhelper.TopicExchangePublish(matRecord, "ZEMT_MQ_EXCHANGE_TTSRESULTTOSCE", "", $"TTSRESULTTOSCE.{linename}"
                , true, false, true, false);
            if (res.Success)
            {
                // 推送成功修改状态3-->4
                SubmitDB.Sumbit_SMDC_Disid(_Disid_T.serial_number, _Disid_T.disidno, State.UploadFinish);
                Logger.Info("数据已推送完成的！");
            }
            else
                Logger.Info("数据推送失败！\n" + res.Message);
        }

        public override void Start()
        {
            DataReceive();
            new Thread(Loop) { IsBackground = true }.Start();
        }
        void DataReceive()
        {
            //配置上传接口
            var res1 = mqhelper.TopicExchangeConsumer<BackResult>((data) =>
            {
                if(data.retcode.Equals("1"))
                {
                    System.Diagnostics.Trace.WriteLine("配置结果接收成功");
                }
                return true;
            }, "ZEMT_MQ_EXCHANGE_TTSRESULTTOSCE", "ZEMT_MQ_SIE_TTSRESULTTOSCE", $"TTSRESULTTOSCE_SIE.{linename}", true, false, true, false);
        }

        public class Retdatas
        {
            /// <summary>
            /// 生产订单号
            /// </summary>
            public string pono { get; set; }
            /// <summary>
            /// 产品物料号
            /// </summary>
            public string pmid { get; set; }
            /// <summary>
            /// 产品序列号
            /// </summary>
            public string productsn { get; set; }
            /// <summary>
            /// 子物料号
            /// </summary>
            public string mid { get; set; }
            /// <summary>
            /// 错误信息
            /// </summary>
            public string errormsg { get; set; }
        }

        public class BackResult
        {
            /// <summary>
            /// 
            /// </summary>
            public string retcode { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string retmsg { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public List<Retdatas> retdatas { get; set; }
        }

    }
}
